//
//  MyDelegate.m
//  MeeffDylib
//
//  Created by global on 2023/11/28.
//

#import "MyDelegate.h"
#import <CoreLocation/CoreLocation.h>
#import <WebKit/WebKit.h>
#import <Security/Security.h>
//#import <Securit

@implementation MyDelegate

// 静态变量来保存唯一的实例
static MyDelegate *sharedInstance = nil;

// 实现类方法，用于获取单例实例
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[super allocWithZone:NULL] init];
        

    });
    return sharedInstance;
}

// 重写 allocWithZone 方法，确保只能通过 sharedInstance 方法创建实例
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self sharedInstance];
}

// 重写 copy 方法，确保只能通过 sharedInstance 方法获取实例
- (id)copyWithZone:(NSZone *)zone {
    return self;
}


// 实现 CLLocationManagerDelegate 方法以获取位置
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    double latitude = location.coordinate.latitude;
    double longitude = location.coordinate.longitude;
    // 使用经纬度
    NSLog(@"定位精度%f  维度%f",latitude,longitude);
    //-119.35,41.11
    //139.37,37.22
    //1.801440, 103.729598 36.398600, 127.887984
    if(self.delegate){
        
        CLLocation* cl =  [MyDelegate randomLocationInKorea];//[[CLLocation alloc]initWithLatitude:36.398600  longitude:127.887984];
//        cl.coordinate
        
        //CLLocationCoordinate2D
        [self.delegate locationManager:manager didUpdateLocations:@[cl]];

    }
    
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // 错误处理
}


// 处理 SSL 证书挑战
- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {

    // 判断是否是证书信任挑战
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        // 创建凭据对象
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        // 忽略证书错误
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    } else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}


+ (NSArray *)getAllKeychainItems {
    NSMutableDictionary *query = [NSMutableDictionary dictionary];

    // 设置查询参数以返回所有项
    [query setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnAttributes];
    [query setObject:(id)kSecMatchLimitAll forKey:(id)kSecMatchLimit];
    [query setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

    // 通过设置 kSecClass 为 kSecClassGenericPassword 来查询密码类别的项
    // 可以修改此处以查询其他类型的项，例如证书或密钥
    [query setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];

    CFTypeRef result = NULL;
    //官方只提供了一个查询接口
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);

    if (status != errSecSuccess) {
        NSLog(@"Error: %d", (int)status);
        return nil;
    }

    return CFBridgingRelease(result);
}

//删除所有keychain
+ (BOOL)deleteAllKeychainItems {
    NSArray *secItemClasses = @[(__bridge id)kSecClassGenericPassword,
                                (__bridge id)kSecClassInternetPassword,
                                (__bridge id)kSecClassCertificate,
                                (__bridge id)kSecClassKey,
                                (__bridge id)kSecClassIdentity];
    for (id secItemClass in secItemClasses) {
        NSDictionary *query = @{(__bridge id)kSecClass: secItemClass};
        OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
        if (status != errSecSuccess && status != errSecItemNotFound) {
            NSLog(@"Error deleting keychain items for class %@: %d", secItemClass, (int)status);
            return NO;
        }
    }
    NSLog(@"All keychain items deleted successfully.");
    return YES;
}

+ (void) load{
    //启动删除钥匙串
//    [MyDelegate deleteAllKeychainItems];
//    NSLog(@"钥匙串%@",[MyDelegate getAllKeychainItems] );
//    [MyDelegate clearAllSandboxData];
//    [MyDelegate deleteWebView];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(appWillTerminate:)
                                                    name:UIApplicationWillTerminateNotification
                                                  object:nil];
////
//    [MyDelegate deletePasteboard];
//    [MyDelegate clearUserDefaults];
    
//     SecCertificateCopyValues(NULL, NULL, NULL);


}

//清除所有数据
+ (void) clearAllData{
    
        [MyDelegate deleteAllKeychainItems];
//        NSLog(@"钥匙串%@",[MyDelegate getAllKeychainItems] );
        [MyDelegate clearAllSandboxData];
        [MyDelegate deleteWebView];
        [MyDelegate deletePasteboard];
        [MyDelegate clearUserDefaults];

}

+ (void)appWillTerminate:(NSNotification *)notification {
    // 在应用终止前执行操作
    NSLog(@"Application is about to terminate (Notification).");
    if([MyDelegate sharedInstance].type == 1){
        [MyDelegate clearAllData];
    }
//
//    [MyDelegate deleteAllKeychainItems];
//    NSLog(@"钥匙串%@",[MyDelegate getAllKeychainItems] );
//    [MyDelegate clearAllSandboxData];
//    [MyDelegate deleteWebView];
//    [MyDelegate deletePasteboard];
//    [MyDelegate clearUserDefaults];
}

//清除应用的沙盒
+ (void)clearAllSandboxData {
    // 获取沙盒中的主要目录路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *tmpDirectory = NSTemporaryDirectory();
    NSString *cachesDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *libraryDirectory = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];

    // 删除这些目录下的所有文件
    [MyDelegate deleteFilesInDirectory:documentsDirectory];
    [MyDelegate deleteFilesInDirectory:tmpDirectory];
    [MyDelegate deleteFilesInDirectory:cachesDirectory];
    [MyDelegate deleteFilesInDirectory:libraryDirectory];
}

+ (void)deleteFilesInDirectory:(NSString *)directoryPath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *directoryContents = [fileManager contentsOfDirectoryAtPath:directoryPath error:&error];

    if (error == nil) {
        for (NSString *path in directoryContents) {
            NSString *fullPath = [directoryPath stringByAppendingPathComponent:path];
            BOOL removeSuccess = [fileManager removeItemAtPath:fullPath error:&error];
            if (!removeSuccess) {
                NSLog(@"Error removing file %@: %@", fullPath, error);
            }
        }
    } else {
        NSLog(@"Error getting contents of directory: %@", error);
    }
}

//清理WebView
+ (void) deleteWebView{
    WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore];
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];

    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [dataStore removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        NSLog(@"All WKWebView data removed.");
    }];
    
    // 创建URLCache实例
    NSURLCache *cache = [NSURLCache sharedURLCache];
    // 清除所有缓存的响应数据
    [cache removeAllCachedResponses];

    // 你还可以选择清除特定请求的缓存
    // [cache removeCachedResponseForRequest:request];

    
}

+ (void) deletePasteboard{
    // 获取系统的通用粘贴板
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    // 清空粘贴板内容
    pasteboard.string = @"";
}


+ (void)clearUserDefaults {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dictionary = [defaults dictionaryRepresentation];

    for (NSString *key in dictionary) {
        [defaults removeObjectForKey:key];
    }

    [defaults synchronize];
}

//随机选择一个版本号
+(NSString* ) randomSystemVersion {
    NSMutableArray *versions = [[NSMutableArray alloc] init];

    // 从14.0.0开始生成到16.9.9的版本号
    for (int major = 14; major <= 16; major++) {
        for (int minor = 0; minor <= 9; minor++) {
            for (int patch = 0; patch <= 9; patch++) {
                NSString *version = [NSString stringWithFormat:@"%d.%d.%d", major, minor, patch];
                [versions addObject:version];
            }
        }
    }

    // 随机选择数组中的一个版本号
    NSUInteger randomIndex = arc4random_uniform((uint32_t)[versions count]);
    
    NSString* randomSystemVersion = [MyDelegate getDevic:localDeviceInfo key:@"randomSystemVersion"];
    if(randomSystemVersion ){
        return  randomSystemVersion;
    }else{
        [MyDelegate saveDevic:localDeviceInfo dic:@{@"randomSystemVersion":versions[randomIndex]}];
        return versions[randomIndex];
    }
    
}
//随机生成电量
+( float) randomBatteryLevel {
    // 随机生成一个介于 0.1 到 1.0 的浮点数
    float randomLevel = (arc4random_uniform(90) + 10) / 100.0f;
    
    NSNumber* randomBatteryLevel = [MyDelegate getDevic:localDeviceInfo key:@"randomBatteryLevel"];
    if(randomBatteryLevel && [randomBatteryLevel isKindOfClass:[NSNumber class]]){
        return  [randomBatteryLevel floatValue];
    }else{
        [MyDelegate saveDevic:localDeviceInfo dic:@{@"randomBatteryLevel":@(randomLevel)}];
        return randomLevel;
    }
    
}
//随机生型号
+(NSString*) randomDeviceModel {
    // 定义一个数组，包含可能的设备型号标识符
    NSArray *models = @[@"iPhone9,1", @"iPhone9,2", @"iPhone9,3", @"iPhone9,4",
                        @"iPhone10,1", @"iPhone10,2", @"iPhone10,3", @"iPhone10,4",
                        @"iPhone10,5", @"iPhone10,6", @"iPhone11,2", @"iPhone11,4",
                        @"iPhone11,6", @"iPhone11,8", @"iPhone12,1", @"iPhone12,3",
                        @"iPhone12,5", @"iPhone12,8", //... 更多型号
                       ];

    // 随机选择数组中的一个型号
    NSString* randomDeviceModel = [MyDelegate getDevic:localDeviceInfo key:@"randomDeviceModel"];
    if(randomDeviceModel ){
        return  randomDeviceModel;
    }else{
        NSUInteger randomIndex = arc4random_uniform((uint32_t)[models count]);
        [MyDelegate saveDevic:localDeviceInfo dic:@{@"randomDeviceModel":models[randomIndex]}];
        return models[randomIndex];
    }
    
    
}

//随机韩国经纬度
 +(CLLocation*) randomLocationInKorea {
    // 韩国的经纬度范围
    double latMin = 33.0;
    double latMax = 38.0;
    double lonMin = 125.0;
    double lonMax = 131.0;
     
     // 日本的经纬度范围
//     double latMin = 24.0;
//     double latMax = 45.0;
//     double lonMin = 122.0;
//     double lonMax = 154.0;
     
    // 生成随机经纬度
    double latitude = latMin + (double)arc4random() / UINT32_MAX * (latMax - latMin);
    double longitude = lonMin + (double)arc4random() / UINT32_MAX * (lonMax - lonMin);
     
     NSNumber* latitudeOBJ = [MyDelegate getDevic:localDeviceInfo key:@"latitude"];
     NSNumber* longitudeOBJ = [MyDelegate getDevic:localDeviceInfo key:@"longitude"];
     if(latitudeOBJ && [latitudeOBJ isKindOfClass:[NSNumber class]]){
         latitude = latitudeOBJ.floatValue;
         longitude = longitudeOBJ.floatValue;
     }else{
         [MyDelegate saveDevic:localDeviceInfo dic:@{@"latitude":@(latitude),@"longitude":@(longitude)}];
     }

    // 创建并返回CLLocation对象
    CLLocation *randomLocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
     
    return randomLocation;
}


//随机存储空间1.1 - 6.1
+(float) randomFloatBetween:(float) smallNumber bigNumber:(float) bigNumber{
    // 产生一个随机浮点数
    NSNumber* randomFloatBetween = [MyDelegate getDevic:localDeviceInfo key:@"randomFloatBetween"];
    if(randomFloatBetween && [randomFloatBetween isKindOfClass:[NSNumber class]]){
        return  [randomFloatBetween floatValue];
    }else{
        float diff = bigNumber - smallNumber;
        float   res = (((float) arc4random() / 0x100000000) * diff) + smallNumber;
        [MyDelegate saveDevic:localDeviceInfo dic:@{@"randomFloatBetween":@(res)}];
        return res;
    }
    
}

//生成uuid
//NSLog(@"广告标识符 特么method  :");
+ (NSUUID*) advertisingIdentifier{
    NSLog(@"广告标识符 特么method  :");
    NSString* advertisingIdentifier = [MyDelegate getDevic:localDeviceInfo key:@"advertisingIdentifier"];
    if(advertisingIdentifier){
        return   [[NSUUID alloc]initWithUUIDString:advertisingIdentifier];
    }else{
        NSUUID* uuidString2 = [NSUUID UUID];
        [MyDelegate saveDevic:localDeviceInfo dic:@{@"advertisingIdentifier":uuidString2.UUIDString}];
        return uuidString2;
    }
}

+ (NSUUID*) identifierForVendor{
    NSLog(@"厂商标识符 特么method  :");
    NSString* identifierForVendor = [MyDelegate getDevic:localDeviceInfo key:@"identifierForVendor"];
    if(identifierForVendor){
        return  [[NSUUID alloc]initWithUUIDString:identifierForVendor];
    }else{
        NSUUID* uuidString2 = [NSUUID UUID];
        [MyDelegate saveDevic:localDeviceInfo dic:@{@"identifierForVendor":uuidString2.UUIDString}];
        return uuidString2;
    }
}


//备份plist
+(void) copyLog:(NSString*) loginName{
    
    // 获取NSUserDefaults的实例
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    // 获取所有键值对
    NSDictionary *defaultsDict = [defaults dictionaryRepresentation];

    // 获取Documents目录的路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString* filename = [NSString stringWithFormat:@"%@.plist",loginName];
    // 设置备份文件的路径
    NSString *backupFilePath = [documentsDirectory stringByAppendingPathComponent:filename];

    // 将NSUserDefaults的数据写入到备份文件
    [defaultsDict writeToFile:backupFilePath atomically:YES];
    // 输出备份文件的路径
    NSLog(@"NSUserDefaults备份文件路径: %@", backupFilePath);
    
}

//还原备份的plist
+ (void) restoreLog:(NSString*) loginName{
    
    // 获取Documents目录的路径
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
       NSString *documentsDirectory = [paths objectAtIndex:0];
       NSString* filename = [NSString stringWithFormat:@"%@.plist",loginName];

       // 设置备份文件的路径
       NSString *backupFilePath = [documentsDirectory stringByAppendingPathComponent:filename];

       // 从备份文件中读取数据
       NSDictionary *backupData = [NSDictionary dictionaryWithContentsOfFile:backupFilePath];

       // 检查是否成功读取数据
       if (backupData) {
           // 获取NSUserDefaults的实例
           NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

           // 遍历备份数据，恢复到NSUserDefaults
           for (NSString *key in backupData) {
               [defaults setObject:[backupData objectForKey:key] forKey:key];
           }

           // 同步NSUserDefaults
           [defaults synchronize];

           NSLog(@"NSUserDefaults数据已从备份恢复。");
       } else {
           NSLog(@"无法从备份文件读取数据。");
       }
   
}


//保存本地数据
+(void)saveDevic:(NSString*) localkey  dic:(NSDictionary*) dic{
    
    NSMutableDictionary*  localdic = [[NSUserDefaults standardUserDefaults] valueForKey:localkey];
    if(localdic){
       NSMutableDictionary*  res = [localdic mutableCopy];
        for(NSString* key in dic.allKeys){
            [res setValue:[dic valueForKey:key] forKey:key];
        }
        [[NSUserDefaults standardUserDefaults] setValue:res forKey:localkey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        NSMutableDictionary*  res = [dic mutableCopy];
        [[NSUserDefaults standardUserDefaults] setValue:res forKey:localkey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

+(id)getDevic:(NSString*) localkey  key:(NSString*) key{
    
    NSMutableDictionary*  localdic = [[NSUserDefaults standardUserDefaults] valueForKey:localkey];
    if(localdic){
        return  [localdic valueForKey:key];
    }
    return nil;
    
}



@end


